package midp;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Graphics;

public class WaitImageCanvas extends DialogCanvas {

	private int mCount, mMaximum;
	private int interval;

	private int mX, mY, mRadius;

	// private boolean run = false;

	public WaitImageCanvas(String message) {
		this(message, 100);
	}
	/**
	 * @param message
	 *            要显示的信息
	 * @param radiusPercent
	 *            动画的百分比
	 */
	public WaitImageCanvas(String message,int radiusPercent) {
		super(message);
		if(!(radiusPercent<= 100 && radiusPercent>0 )){
			throw new IllegalArgumentException("radiusPercent的值无效范围(0-100]!当前值:"+radiusPercent);
		}

		final boolean run=true;
		mCount = 0;
		mMaximum = 36;
		interval = 100;

		int mWidth = getWidth();
		int mHeight = getHeight();

		// Calculate the radius.
		int halfWidth = (mWidth - mRadius) / 2;
		int halfHeight = (mHeight - mRadius) / 2;
		mRadius = Math.min(halfWidth, halfHeight);
		if(radiusPercent < 100){
			mRadius = (mRadius*radiusPercent) /100;
		}

		// Calculate the location.
		mX = halfWidth - mRadius / 2;
		mY = halfHeight - mRadius / 2;

		// Create a Timer to update the display.
		if (run) {
			TimerTask task = new TimerTask() {
				public void run() {
					mCount = (mCount + 1) % mMaximum;
					repaint();
				}
			};
			Timer timer = new Timer();

			timer.schedule(task, 0, interval);
		}
	}

	public void paint(Graphics g) {
		int theta = -(mCount * 360 / mMaximum);

		int mWidth = getWidth();
		int mHeight = getHeight();

		// Clear the whole screen.
		g.setColor(255, 255, 255);
		g.fillRect(0, 0, mWidth, mHeight);

		// Now draw the pinwheel.
		g.setColor(this.getFrontColor());
		g.drawArc(mX, mY, mRadius, mRadius, 0, 360);
		g.fillArc(mX, mY, mRadius, mRadius, theta + 90, 90);
		g.fillArc(mX, mY, mRadius, mRadius, theta + 270, 90);
		// Draw the message, if there is a message.
		final String message = this.getMessage();
		if (message != null) {
			g.drawString(message, mWidth / 2, mHeight, Graphics.BOTTOM
					| Graphics.HCENTER);
		}
	}

}
